<template>
  <div class="script-ranking">
    <div class="ranking-header">
      <h2>剧本排行榜</h2>
      <div class="ranking-tabs">
        <button
          @click="changeTab('usage')"
          :class="{ active: activeTab === 'usage' }"
          class="tab-btn"
          :disabled="isLoading"
        >
          使用排行
        </button>
        <button
          @click="changeTab('likes')"
          :class="{ active: activeTab === 'likes' }"
          class="tab-btn"
          :disabled="isLoading"
        >
          点赞排行
        </button>
        <button
          @click="changeTab('comprehensive')"
          :class="{ active: activeTab === 'comprehensive' }"
          class="tab-btn"
          :disabled="isLoading"
        >
          综合排行
        </button>
      </div>
    </div>

    <div class="ranking-content">
      <!-- 加载状态 -->
      <div v-if="isLoading && scripts.length === 0" class="loading-placeholder">
        <div v-for="n in 5" :key="n" class="ranking-skeleton">
          <div class="skeleton-rank"></div>
          <div class="skeleton-content">
            <div class="skeleton-title"></div>
            <div class="skeleton-meta"></div>
          </div>
          <div class="skeleton-stats"></div>
          <div class="skeleton-actions"></div>
        </div>
      </div>

      <div v-else class="ranking-list">
        <div
          v-for="(script, index) in rankedScripts"
          :key="script.id"
          class="ranking-item"
          :class="{ 'top-three': index < 3 }"
        >
          <div class="rank-number">
            <span class="rank">{{ index + 1 }}</span>
            <div v-if="index < 3" class="medal">
              <span v-if="index === 0" class="gold">🥇</span>
              <span v-else-if="index === 1" class="silver">🥈</span>
              <span v-else class="bronze">🥉</span>
            </div>
          </div>

          <div class="script-info">
            <div class="script-header">
              <h3 class="script-name">{{ script.name }}</h3>
              <span class="script-author"
                >by {{ script.author || "未知" }}</span
              >
            </div>
            <div class="script-meta">
              <span class="category">{{ getCategoryDisplayName(script.category) }}</span>
              <span class="level">{{ script.level || "Intermediate" }}</span>
              <span class="roles-count"
                >{{ script.roles?.length || 0 }} 角色</span
              >
            </div>
            <p class="description">{{ script.description || "暂无描述" }}</p>
          </div>

          <div class="script-stats">
            <div class="stat-item">
              <span class="stat-label">使用次数</span>
              <span class="stat-value usage">{{ script.usage || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">点赞数</span>
              <span class="stat-value likes">{{ script.likes || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">综合评分</span>
              <span class="stat-value score">{{ calculateScore(script) }}</span>
            </div>
          </div>

          <div class="script-actions">
            <button @click="useScript(script.id)" class="use-btn">使用</button>
            <button @click="likeScript(script.id)" class="like-btn">
              <span v-if="script.isLiked">❤️</span>
              <span v-else>🤍</span>
            </button>
            <button @click="viewScript(script)" class="view-btn" title="查看剧本详情">
              查看
            </button>
          </div>
        </div>

        <!-- 加载更多按钮 -->
        <div v-if="showLoadMore" class="load-more-container">
          <button @click="loadMore" class="load-more-btn" :disabled="isLoadingMore">
            <span v-if="isLoadingMore">加载中...</span>
            <span v-else>加载更多</span>
          </button>
        </div>

        <!-- 加载更多状态 -->
        <div v-if="isLoadingMore" class="loading-more">
          <div v-for="n in 3" :key="n" class="ranking-skeleton">
            <div class="skeleton-rank"></div>
            <div class="skeleton-content">
              <div class="skeleton-title"></div>
              <div class="skeleton-meta"></div>
            </div>
            <div class="skeleton-stats"></div>
            <div class="skeleton-actions"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 剧本详情模态框 -->
    <ScriptDetailModal 
      :show="showDetailModal"
      :scriptId="selectedScriptId"
      :scriptType="selectedScriptType"
      @close="closeDetailModal"
      @use-script-complete="handleUseScriptComplete"
    />
  </div>
</template>

<script>
import scriptAPI from "@/utils/scriptAPI";
import systemAPI from "@/utils/systemAPI";
import ScriptDetailModal from "./ScriptDetailModal.vue";

export default {
  name: "ScriptRanking",
  components: {
    ScriptDetailModal,
  },
  data() {
    return {
      activeTab: "usage",
      scripts: [],
      isLoading: false,
      currentPage: 1,
      itemsPerPage: 20, // 每页显示20个剧本
      hasMore: true,
      isLoadingMore: false,
      totalCount: 0,
      categories: [],
      isLoadingCategories: false,
      // 剧本详情模态框相关
      showDetailModal: false,
      selectedScriptId: "",
      selectedScriptType: "custom",
    };
  },
  computed: {
    rankedScripts() {
      // 不在这里排序，因为数据已经在服务端排序好了
      return this.scripts;
    },
    // 是否显示加载更多按钮
    showLoadMore() {
      return this.hasMore && !this.isLoading && !this.isLoadingMore;
    },
    // 当前排序类型的中文名称
    sortTypeName() {
      const typeMap = {
        'usage': '使用次数',
        'likes': '点赞数',
        'comprehensive': '综合评分'
      };
      return typeMap[this.activeTab] || '未知';
    },
    // 活跃的分类列表（和ScriptBrowser保持一致）
    activeCategories() {
      return this.categories.filter(category => category.isActive);
    },
  },
  async mounted() {
    await this.loadCategories();
    await this.loadScripts();
  },
  methods: {
    async loadScripts(loadMore = false) {
      try {
        if (loadMore) {
          this.isLoadingMore = true;
        } else {
        this.isLoading = true;
          this.currentPage = 1;
          this.scripts = [];
        }

        const params = {
          page: this.currentPage,
          limit: this.itemsPerPage,
          sortBy: this.activeTab, // 使用当前激活的标签作为排序依据
          status: 'approved' // 只显示已审核的剧本
        };

        console.log(`🔍 加载排行榜数据 (${this.sortTypeName})`, {
          page: this.currentPage,
          limit: this.itemsPerPage,
          sortBy: this.activeTab,
          loadMore: loadMore
        });

        const result = await scriptAPI.getAllScripts(params);

        if (result.success && result.data && Array.isArray(result.data.scripts)) {
          const newScripts = result.data.scripts;
          
          // 批量获取统计数据（优化：并行处理但限制并发数）
          const batchSize = 5; // 每批处理5个剧本
          const scriptsWithStats = [];
          
          for (let i = 0; i < newScripts.length; i += batchSize) {
            const batch = newScripts.slice(i, i + batchSize);
            const batchResults = await Promise.all(
              batch.map(async (script) => {
                try {
                  // 并行获取使用和点赞统计
                  const [usageResult, likesResult] = await Promise.all([
                    scriptAPI.getScriptUsage(script.id),
                    scriptAPI.getScriptLikes(script.id)
                  ]);

                const usage = usageResult.success ? usageResult.data.count : 0;
                const likes = likesResult.success ? likesResult.data.count : 0;
                const isLiked = likesResult.success ? likesResult.data.isLiked : false;

                return {
                  ...script,
                  usage,
                  likes,
                  isLiked
                };
              } catch (error) {
                console.error(`获取剧本 ${script.id} 统计数据失败:`, error);
                return {
                  ...script,
                  usage: 0,
                  likes: 0,
                  isLiked: false
                };
              }
            })
          );
            scriptsWithStats.push(...batchResults);
          }

          // 根据当前排序类型进行排序
          scriptsWithStats.sort((a, b) => {
            switch (this.activeTab) {
              case "usage":
                return (b.usage || 0) - (a.usage || 0);
              case "likes":
                return (b.likes || 0) - (a.likes || 0);
              case "comprehensive":
                return this.calculateScore(b) - this.calculateScore(a);
              default:
                return 0;
            }
          });

          if (loadMore) {
            this.scripts.push(...scriptsWithStats);
          } else {
          this.scripts = scriptsWithStats;
          }

          // 更新分页信息
          const pagination = result.data.pagination;
          if (pagination) {
            this.totalCount = pagination.total;
            this.hasMore = this.currentPage < pagination.totalPages;
          } else {
            this.hasMore = scriptsWithStats.length === this.itemsPerPage;
          }

          console.log('✅ 排行榜数据加载完成:', {
            currentPage: this.currentPage,
            loadedCount: scriptsWithStats.length,
            totalScripts: this.scripts.length,
            hasMore: this.hasMore,
            totalCount: this.totalCount
          });
        } else {
          if (!loadMore) {
          this.scripts = [];
          }
          this.hasMore = false;
        }
      } catch (error) {
        console.error("❌ 加载排行榜数据错误:", error);
        if (!loadMore) {
        this.scripts = [];
        }
        this.hasMore = false;
      } finally {
        this.isLoading = false;
        this.isLoadingMore = false;
      }
    },

    calculateScore(script) {
      const usage = script.usage || 0;
      const likes = script.likes || 0;
      return Math.round(usage * 0.6 + likes * 0.4);
    },

    async useScript(scriptId) {
      try {
        // 找到对应的剧本对象
        const script = this.scripts.find((s) => s.id === scriptId);
        if (!script) {
          throw new Error('未找到对应的剧本');
        }

        // 记录使用次数
        const result = await scriptAPI.useScript(scriptId);
        if (result.success) {
          // 获取剧本的完整数据并设置为当前剧本
          const scriptResult = await scriptAPI.getScript(scriptId, script.type || 'custom');
          if (scriptResult.success && scriptResult.data) {
            const scriptData = scriptResult.data;
            
            // 如果剧本包含角色数据，设置自定义角色
            if (scriptData.content && Array.isArray(scriptData.content)) {
              // 过滤掉_meta数据，只保留角色
              const roles = scriptData.content.filter(item => item.id !== '_meta');
              this.$store.commit("setCustomRoles", roles);
            }
            
            // 设置剧本版本信息
            this.$store.commit("setEdition", {
              id: script.id,
              name: script.name,
              author: script.author || "未知作者",
              description: script.description || "",
              isOfficial: false
            });

            // 更新使用统计
          const usageResult = await scriptAPI.getScriptUsage(scriptId);
          if (usageResult.success) {
              script.usage = usageResult.data.count;
            }
            
            // 关闭排行榜窗口并通知父组件关闭整个剧本浏览器
            this.$emit('close');
            this.$emit('close-all'); // 新增事件：通知关闭所有相关界面
            
            console.log(`✅ 剧本"${script.name}"已加载成功并进入游戏！`);
            this.$emit('script-used', { scriptId, success: true });
          } else {
            throw new Error('获取剧本数据失败');
          }
        } else {
          console.error("使用剧本失败:", result.error);
          this.$emit('script-used', { scriptId, success: false, error: result.error });
        }
      } catch (error) {
        console.error("❌ 使用剧本失败:", error);
        this.$emit('script-used', { scriptId, success: false, error: error.message });
      }
    },

    async likeScript(scriptId) {
      try {
        const result = await scriptAPI.toggleLike(scriptId);
        if (result.success) {
          // 获取最新的点赞统计
          const likesResult = await scriptAPI.getScriptLikes(scriptId);
          if (likesResult.success) {
            const script = this.scripts.find((s) => s.id === scriptId);
            if (script) {
              script.likes = likesResult.data.count;
              script.isLiked = likesResult.data.isLiked;
            }
          }
        }
      } catch (error) {
        console.error("点赞失败:", error);
      }
    },

    viewScript(script) {
      console.log("🔍 查看剧本详情:", script);
      if (script && script.id) {
        this.selectedScriptId = script.id;
        // 根据剧本ID判断剧本类型，通常以数字结尾的是自定义剧本
        this.selectedScriptType = script.id.includes('_') ? 'custom' : 'official';
        this.showDetailModal = true;
      } else {
        console.error("无效的剧本数据:", script);
      }
    },

    closeDetailModal() {
      this.showDetailModal = false;
      this.selectedScriptId = "";
      this.selectedScriptType = "custom";
    },

    handleUseScriptComplete() {
      // 剧本使用完成后，关闭排行榜界面，返回游戏界面
      console.log("🎮 剧本使用完成，关闭排行榜界面");
      this.closeDetailModal(); // 关闭详情模态框
      this.$emit("close"); // 关闭排行榜界面
    },

    async loadCategories() {
      try {
        this.isLoadingCategories = true;
        const result = await systemAPI.getCategories();
        if (result.success) {
          this.categories = result.data.categories || [];
        } else {
          console.error('加载分类失败:', result.error);
        }
      } catch (error) {
        console.error('加载分类失败:', error);
      } finally {
        this.isLoadingCategories = false;
      }
    },

    getCategoryDisplayName(category) {
      // 与ScriptBrowser保持一致的分类显示逻辑
      const categoryObj = this.categories.find(c => c.id === category);
      return categoryObj ? categoryObj.name : (category || "未分类");
    },

    // 加载更多数据
    async loadMore() {
      if (this.isLoadingMore || !this.hasMore) return;
      
      this.currentPage++;
      await this.loadScripts(true);
    },

    // 切换排序类型
    async changeTab(tab) {
      if (this.activeTab === tab) return;
      
      this.activeTab = tab;
      await this.loadScripts(false); // 重新加载数据
    },

    // 刷新当前数据
    async refresh() {
      await this.loadScripts(false);
    },

  },
};
</script>

<style scoped lang="scss">
.script-ranking {
  padding: 0; // 移除内边距，因为外层模态框已经有padding
  max-width: 100%; // 占满容器宽度
  margin: 0;
  height: 100%; // 确保高度填满容器
}

.ranking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;

  h2 {
    margin: 0;
    color: #fff;
    font-size: 24px;
  }

  .ranking-tabs {
    display: flex;
    gap: 10px;

    .tab-btn {
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      background: #333;
      color: #ccc;
      transition: all 0.3s ease;

      &.active {
        background: #4a90e2;
        color: #fff;
      }

      &:hover {
        background: #4a90e2;
        color: #fff;
      }
    }
  }
}

.ranking-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.ranking-item {
  display: grid;
  grid-template-columns: 80px 1fr 150px 120px;
  gap: 20px;
  background: #2a2a2a;
  border-radius: 8px;
  padding: 20px;
  align-items: center;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  }

  &.top-three {
    border: 2px solid;

    &:nth-child(1) {
      border-color: #ffd700;
      background: linear-gradient(135deg, #2a2a2a 0%, #3a3a2a 100%);
    }

    &:nth-child(2) {
      border-color: #c0c0c0;
      background: linear-gradient(135deg, #2a2a2a 0%, #2a2a3a 100%);
    }

    &:nth-child(3) {
      border-color: #cd7f32;
      background: linear-gradient(135deg, #2a2a2a 0%, #3a2a2a 100%);
    }
  }

  .rank-number {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;

    .rank {
      font-size: 24px;
      font-weight: bold;
      color: #fff;
    }

    .medal {
      font-size: 20px;
    }
  }

  .script-info {
    .script-header {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 8px;

      .script-name {
        margin: 0;
        color: #fff;
        font-size: 16px;
        font-weight: bold;
      }

      .script-author {
        color: #4a90e2;
        font-size: 12px;
      }
    }

    .script-meta {
      display: flex;
      gap: 15px;
      margin-bottom: 8px;

      span {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 11px;
        background: #333;
        color: #ccc;
      }
    }

    .description {
      color: #ccc;
      font-size: 12px;
      line-height: 1.4;
      margin: 0;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }

  .script-stats {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .stat-label {
        color: #ccc;
        font-size: 11px;
      }

      .stat-value {
        font-weight: bold;
        font-size: 14px;

        &.usage {
          color: #27ae60;
        }

        &.likes {
          color: #e74c3c;
        }

        &.score {
          color: #f39c12;
        }
      }
    }
  }

  .script-actions {
    display: flex;
    flex-direction: column;
    gap: 8px;

    button {
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;

      &.use-btn {
        background: #27ae60;
        color: #fff;

        &:hover {
          background: #229954;
        }
      }

      &.like-btn {
        background: #e74c3c;
        color: #fff;

        &:hover {
          background: #c0392b;
        }
      }

      &.view-btn {
        background: #4a90e2;
        color: #fff;
        transition: all 0.3s ease;

        &:hover {
          background: #357abd;
          transform: scale(1.05);
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }
}

// 骨架屏样式
.loading-placeholder {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.ranking-skeleton {
  display: grid;
  grid-template-columns: 80px 1fr 150px 120px;
  gap: 20px;
  background: #2a2a2a;
  border-radius: 8px;
  padding: 20px;
  align-items: center;

  .skeleton-rank {
    width: 40px;
    height: 40px;
    background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 50%;
  }

  .skeleton-content {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .skeleton-title {
      width: 70%;
      height: 20px;
      background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
    }

    .skeleton-meta {
      width: 50%;
      height: 12px;
      background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
    }
  }

  .skeleton-stats {
    display: flex;
    flex-direction: column;
    gap: 8px;

    &::before,
    &::after {
      content: '';
      width: 100%;
      height: 12px;
      background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
    }
  }

  .skeleton-actions {
    display: flex;
    flex-direction: column;
    gap: 8px;

    &::before,
    &::after {
      content: '';
      width: 100%;
      height: 24px;
      background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
    }
  }
}

@keyframes skeleton-loading {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

// 加载更多样式
.load-more-container {
  display: flex;
  justify-content: center;
  padding: 30px 0;

  .load-more-btn {
    padding: 12px 24px;
    background: #4a90e2;
    color: #fff;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover:not(:disabled) {
      background: #357abd;
      transform: translateY(-1px);
    }

    &:disabled {
      background: #666;
      cursor: not-allowed;
    }
  }
}

.loading-more {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

// 按钮禁用状态
.tab-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
